package com.hntx.joymusic.util;



import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.text.TextUtils;

import com.blankj.utilcode.utils.NetworkUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class SetNetWorkUtils {

    public static final int TYPE_AP = 0;
    public static final int TYPE_WIFI = 1;
    public static final int TYPE_NULL = -1;
    public static final int TYPE_ETHERNET = 9;

    public static final String NETWORK_TYPE = "network_type";
    public static final String NETWORK_IP = "network_ip";
    public static final String NETWORK_MAC = "network_mac";
    public static final String NETWORK_NAME = "network_name";

    private static WifiManager wm;
    private static ConnectivityManager cm;
    public static final String TAG = "NetorkUtils";
    private static SetNetWorkUtils instance = null;
    private static Context context;

    public static SetNetWorkUtils getInstance(Context context) {
        SetNetWorkUtils.context = context;
        initPlatform();
        if (instance == null) {
            synchronized (NetworkUtils.class) {
                if (instance == null) {
                    instance = new SetNetWorkUtils();
                }
            }
        }
        return instance;
    }

    private static void initPlatform() {
        if (wm == null) {
            wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        }

        if (cm == null) {
            cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        }
    }

    public static int getNetworkType() {
        if (isWifiApEnabled()) {
            return TYPE_AP;
        } else {
            NetworkInfo info = cm.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                    return TYPE_ETHERNET;
                } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                    return TYPE_WIFI;
                } else {
                    return TYPE_NULL;
                }
            } else {
                return TYPE_NULL;
            }
        }
    }

    public static String getNetworkName() {
        String ssid = "net unknown";
        int type = getNetworkType();
        switch (type) {
            case TYPE_AP:
                ssid = getNetworkSSID();
                break;
            case TYPE_WIFI:
                String str = wm.getConnectionInfo().getSSID();
                if (!TextUtils.isEmpty(str)) {
                    str = str.substring(1, str.length() - 1);
                }
                ssid = str;
                break;
            case TYPE_ETHERNET:
                ssid = "有线网络";
                break;
            case TYPE_NULL:
                ssid = "未知网络";
                break;

            default:
                break;
        }

        return ssid;
    }

    public String getNetworkIP() {
        String address = "";
        int type = getNetworkType();
        switch (type) {
            case TYPE_AP:
                address = "192.168.43.1";
                break;
            case TYPE_WIFI:
                int ip = wm.getConnectionInfo().getIpAddress();
                address = ((ip & 0xff) + "." + (ip >> 8 & 0xff) + "." + (ip >> 16 & 0xff) + "." + (ip >> 24 & 0xff));
                break;
            case TYPE_ETHERNET:
                address = localAddress();
                break;
            case TYPE_NULL:
                break;

            default:
                break;
        }
        return address;
    }

    public String getNetworkMac() {
        String mac = "";
        int type = getNetworkType();
        switch (type) {
            case TYPE_AP:
                mac = wm.getConnectionInfo().getMacAddress();
                if (mac == null) {
                    mac = UUID.randomUUID().toString();
                }
                break;
            case TYPE_WIFI:
//                mac = wm.getConnectionInfo().getMacAddress();
                mac = localWifiMac();
                if (mac == null) {
                    mac = UUID.randomUUID().toString();
                }
                break;
            case TYPE_ETHERNET:
                mac = localMac();
                break;
            case TYPE_NULL:
                break;

            default:
                break;
        }
        return mac.toUpperCase();
    }

    private static String getNetworkSSID() {
        try {
            Method method = wm.getClass().getMethod("getWifiApConfiguration");
            method.setAccessible(true);
            WifiConfiguration configuration = (WifiConfiguration) method.invoke(wm);
            return configuration.SSID;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "net unknown";
    }

    public static boolean isWifiApEnabled() {
        try {
            Method method = wm.getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(wm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String loadReadFile(String path) {
        StringBuffer sb = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(path));
            char[] buf = new char[8192];
            int len = 0;
            while ((len = reader.read(buf)) != -1) {
                String str = String.valueOf(buf, 0, len);
                sb.append(str);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public String localAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                String interfaceName = intf.getDisplayName();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    Pattern p = Pattern.compile("^[1-9][0-9]*.[0-9][0-9]*.[0-9][0-9]*.[0-9][0-9]*$");
                    Matcher m = p.matcher(inetAddress.getHostAddress().toString());
                    if (!inetAddress.isLoopbackAddress() && m.matches() && interfaceName.equals("eth0")) {
                        String address = inetAddress.getHostAddress().toString();
                        return address;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String localMac() {
        try {
            return loadReadFile("/sys/class/net/eth0/address").toUpperCase().substring(0, 17);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public String localWifiMac() {
        try {
            return loadReadFile("/sys/class/net/wlan0/address").toUpperCase().substring(0, 17);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public Map getAllNetworkInfo() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put(NETWORK_TYPE, getNetworkType());
        map.put(NETWORK_IP, getNetworkIP());
        map.put(NETWORK_MAC, getNetworkMac());
        map.put(NETWORK_NAME, getNetworkName());
        return map;
    }

    public void startAP() {
        if (wm.isWifiEnabled()) {
            startAP(getNetworkSSID(), "12345678");
        }
    }

    private void startAP(String ssid, String password) {
        Method method1 = null;
        try {
            method1 = wm.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
            WifiConfiguration netConfig = new WifiConfiguration();

            netConfig.SSID = ssid;
            netConfig.preSharedKey = password;

            netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            method1.invoke(wm, netConfig, true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 检查当前网络是否可用
     *
     * @return
     */

    public boolean isNetworkAvailable(Context activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
//                    System.out.println(i + "===状态===" + networkInfo[i].getState());
//                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static String getGateWay(Context context) {

        if (wm != null) {
            DhcpInfo dhcpInfo = wm.getDhcpInfo();
//            Log.e("gateway is ", GateWayUtils.long2ip(dhcpInfo.gateway));
            if (!TextUtils.isEmpty(GateWayUtils.long2ip(dhcpInfo.gateway))) {
                return GateWayUtils.long2ip(dhcpInfo.gateway);
            }
        } else {

            try {
                for (Enumeration<NetworkInterface> en = NetworkInterface
                        .getNetworkInterfaces(); en.hasMoreElements(); ) {
                    NetworkInterface intf = en.nextElement();

                    for (Enumeration<InetAddress> enumIpAddr = intf
                            .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            String ipAddress = inetAddress.getHostAddress().toString();

                            if (!ipAddress.contains("::"))
                                return inetAddress.getHostAddress().toString();
                        } else
                            continue;
                    }
                }
            } catch (Exception ex) {
//                Log.e("abc", ex.toString());
            }
        }
        return null;
    }
}

